package com.yurembo.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.yurembo.entity.Goods;
import com.yurembo.service.GoodsService;

@Controller
@RequestMapping("/")
public class BaseController {
	
	@Autowired
	private GoodsService goodsService;
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String welcome(Model model) {
		model.addAttribute("message", "Maven Web Project + Spring 3 MVC + Hibernate");
		List<Goods> goodsList = new ArrayList<>(goodsService.getAllGoods());
		if (goodsList.size() > 0) {
			model.addAttribute("goods", goodsList);
		} 
		return "index";
	}
	
	@RequestMapping(value = "/", method = RequestMethod.POST)
	public String addGoods(@ModelAttribute Goods goods, BindingResult bindingResult) {
		goodsService.addGoods(goods);
		return "redirect:/";
	}
}